﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Web.Script.Serialization;

namespace Common
{
    public class JsonHelper
    {
    
        /// <summary>
        /// 生成Json格式
        /// </summary>
        /// <typeparam name="T">(泛型)</typeparam>
        /// <param name="obj">待转换的类型</param>
        /// <returns></returns>
        public static string GetJson<T>(T obj)
        {
            DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType());
            using (MemoryStream stream = new MemoryStream())
            {
                json.WriteObject(stream, obj);

                string szJson = Encoding.UTF8.GetString(stream.ToArray()); return szJson;
            }
        }

        /// <summary>
        /// 获取Json的Model
        /// </summary>
        /// <typeparam name="T">(泛型)</typeparam>
        /// <param name="szJson">待转换的json字符串</param>
        /// <returns></returns>
        public static T ParseFromJson<T>(string szJson)
        {
            if (string.IsNullOrEmpty(szJson))
            {
                return default(T);
            }
            T obj = Activator.CreateInstance<T>();
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                return (T)serializer.ReadObject(ms);
            }
        }


        /// <summary>
        /// 生成Json格式
        /// </summary>
        /// <param name="obj">待转换的类型</param>
        /// <returns></returns>
        public static string Serialize<T>(T obj)
        {
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            return Serializer.Serialize(obj);
        }

        /// <summary>
        /// 生成Json格式
        /// </summary>
        /// <param name="obj">待转换的类型</param>
        /// <returns></returns>
        [Obsolete("此方法有缺陷,建议用泛型的方法")]
        public static string Serialize(object obj)
        {
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            return Serializer.Serialize(obj).Trim('\'').Replace("\\","\\\\");
        }

        /// <summary>
        /// 获取Json的Model
        /// </summary>
        /// <typeparam name="T">(泛型)</typeparam>
        /// <param name="szJson">待转换的json字符串</param>
        /// <returns></returns>
        public static T Deserialize<T>(string szJson)
        {
            if (string.IsNullOrEmpty(szJson))
            {
                return default(T);
            }
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            T obj = Serializer.Deserialize<T>(szJson);
            return obj;
        }
    }
}
